import React, { ReactNode } from 'react'
import { View, Text, StyleSheet } from 'react-native'

interface Props {
  radius: number; // 半径
  borderWidth: number; // 圆环宽度
  color: string; // 圆环颜色
  shadowColor: string; // 圆环背景色
  backColor: string; // 圆的背景色
  percent: number; // 百分比
}
interface State {
  baseCirleStyle: object;
}

export default class Progress extends React.Component<Props, State> {
  public static defaultProps = {
    radius: 25,
    borderWidth: 5,
    color: '#7fa2ff',
    shadowColor: '#ecf0fc',
    backColor: '#fff',
    percent: 90
  }

  public constructor (props: Props) {
    super(props)
    this.state = {
      baseCirleStyle: {
        width: this.props.radius * 2,
        height: this.props.radius * 2,
        borderRadius: this.props.radius
      }
    }
  }

  public renderHalfCircle (rotateNum: number = 0): ReactNode {
    return (
      <View style={[
        this.state.baseCirleStyle,
        {
          width: this.props.radius,
          borderRadius: this.props.radius * 2,
          backgroundColor: rotateNum > 0 ? this.props.color : this.props.shadowColor,
          transform: [
            { translateX: this.props.radius / 2 },
            { rotate: `${rotateNum}deg` },
            { translateX: -this.props.radius / 2 }
          ]
        },
        styles.half_circle
      ]} />
    )
  }

  public renderInnerCircle (): ReactNode {
    const { radius, borderWidth, backColor } = this.props
    return (
      <View style={[styles.inner_circle, {
        top: borderWidth,
        left: borderWidth,
        height: (radius - borderWidth) * 2,
        width: (radius - borderWidth) * 2,
        borderRadius: radius - borderWidth,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: backColor
      }]}>
        {this.props.children || <Text style={{ color: this.props.color }}>{this.props.percent}%</Text>}
      </View>
    )
  }

  public render (): ReactNode {
    return (
      <View style={[styles.border, this.state.baseCirleStyle]}>
        {/* 背景环 */}
        <View style={[styles.back_circle, this.state.baseCirleStyle, { backgroundColor: this.props.shadowColor }]} />
        {this.renderHalfCircle(this.props.percent > 50 ? 180 : this.props.percent * 3.6)}
        {this.renderHalfCircle(this.props.percent > 50 ? this.props.percent * 3.6 : 0)}
        {this.renderInnerCircle()}
      </View>
    )
  }
}
const styles = StyleSheet.create({
  border: {
    alignItems: 'center',
    justifyContent: 'center',
    position: 'relative'
  },
  back_circle: {
    position: 'absolute',
    left: 0,
    top: 0
  },
  inner_circle: {
    position: 'absolute'
  },
  half_circle: {
    position: 'absolute',
    left: 0,
    top: 0,
    borderTopRightRadius: 0,
    borderBottomRightRadius: 0
  }
})
